#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
import argparse
from pathlib import Path


def find_markdown_images(markdown_file):
    """查找Markdown文件中的所有图片引用"""
    if not os.path.exists(markdown_file):
        print(f"警告：Markdown文件 {markdown_file} 不存在")
        return set()
    
    with open(markdown_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 匹配Markdown中的图片引用: ![alt](path) 或 <img src="path">
    image_patterns = [
        r'!\[[^\]]*\]\(([^)]+)\)',  # 匹配 ![alt](path)
        r'<img\s+src=["\']([^"\']+)["\']',  # 匹配 <img src="path"> 或 <img src='path'>
    ]
    
    used_images = set()
    for pattern in image_patterns:
        matches = re.findall(pattern, content)
        for match in matches:
            # 获取文件名（不包含路径）
            image_name = os.path.basename(match)
            used_images.add(image_name)
    
    return used_images


def get_assets_images(assets_dir):
    """获取assets目录中的所有图片文件"""
    if not os.path.exists(assets_dir):
        print(f"警告：assets目录 {assets_dir} 不存在")
        return set()
    
    # 常见图片扩展名
    image_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.svg', '.webp'}
    
    assets_images = set()
    for file in os.listdir(assets_dir):
        file_path = os.path.join(assets_dir, file)
        if os.path.isfile(file_path):
            _, ext = os.path.splitext(file.lower())
            if ext in image_extensions:
                assets_images.add(file)
    
    return assets_images


def cleanup_unused_images(markdown_file, assets_dir, dry_run=False):
    """清理在Markdown中未引用的图片"""
    # 获取Markdown中引用的图片和assets中的图片
    used_images = find_markdown_images(markdown_file)
    assets_images = get_assets_images(assets_dir)
    
    # 找出未引用的图片
    unused_images = assets_images - used_images
    
    if not unused_images:
        print("没有发现未引用的图片")
        return
    
    print(f"发现 {len(unused_images)} 个未引用的图片:")
    for image in unused_images:
        print(f"  - {image}")
    
    # 删除未引用的图片
    if not dry_run:
        for image in unused_images:
            image_path = os.path.join(assets_dir, image)
            try:
                os.remove(image_path)
                print(f"已删除: {image_path}")
            except Exception as e:
                print(f"删除失败 {image_path}: {e}")
    else:
        print("这是模拟运行，未实际删除任何文件")


def main():
    parser = argparse.ArgumentParser(description='清理Markdown中未引用的图片')
    parser.add_argument('--markdown', '-m', 
                        default='readme.md', 
                        help='Markdown文件路径 (默认: readme.md)')
    parser.add_argument('--assets', '-a', 
                        default='assets', 
                        help='图片资产目录路径 (默认: assets)')
    parser.add_argument('--dry-run', '-d', 
                        action='store_true', 
                        help='模拟运行，不实际删除文件')
    
    args = parser.parse_args()
    
    # 转换为绝对路径
    markdown_file = os.path.abspath(args.markdown)
    assets_dir = os.path.abspath(args.assets)
    
    print(f"检查Markdown文件: {markdown_file}")
    print(f"检查Assets目录: {assets_dir}")
    
    cleanup_unused_images(markdown_file, assets_dir, args.dry_run)


if __name__ == '__main__':
    main()